<template>
    <div class="aliyun-oss-config">
        <div class="card-wrap mb10 animate-on-enter">
            <a-space wrap>
                <a-button :icon="h(ReloadOutlined)" @click="onRefresh" :loading="loading">
                    刷新
                </a-button>
            </a-space>
        </div>

        <div class="card-wrap mb10 animate-on-enter animate-delay-1">
            <a-alert :message="formState.description" type="info" show-icon />
            <div class="mt10">
                <a-typography-text type="secondary">
                    需要帮助？请参考：
                    <a href="https://help.aliyun.com/zh/ram/product-overview/what-is-sts?spm=a2c4g.11186623.help-menu-28625.d_0_0_1.38b0595c6QRNqr&scm=20140722.H_28756._.OR_help-T_cn~zh-V_1" target="_blank">
                        阿里云STS服务文档
                    </a>
                </a-typography-text>
            </div>
        </div>

        <div class="card-wrap animate-on-enter animate-delay-2">
            <a-spin :spinning="loading">
                <a-form ref="formRef" :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }"
                    :rules="rules" @finish="onSubmit" @finishFailed="onFinishFailed">
                    <a-form-item label="AccessKey ID" :name="['config_value', 'accessKeyId']">
                        <a-input v-model:value="formState.config_value.accessKeyId" placeholder="请输入阿里云AccessKey ID" />
                    </a-form-item>

                    <a-form-item label="AccessKey Secret" :name="['config_value', 'accessKeySecret']">
                        <a-input-password v-model:value="formState.config_value.accessKeySecret"
                            placeholder="请输入阿里云AccessKey Secret" />
                    </a-form-item>

                    <a-form-item label="regionId" :name="['config_value', 'regionId']">
                        <a-input v-model:value="formState.config_value.regionId" placeholder="请输入地域ID，如：cn-hangzhou" />
                    </a-form-item>

                    <a-form-item label="RoleArn" :name="['config_value', 'RoleArn']">
                        <a-input v-model:value="formState.config_value.RoleArn" placeholder="请输入RAM角色ARN" />
                    </a-form-item>

                    <a-form-item label="Bucket" :name="['config_value', 'RoleSessionName']">
                        <a-input v-model:value="formState.config_value.RoleSessionName" placeholder="请输入Bucket名称" />
                    </a-form-item>

                    <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
                        <a-button type="primary" :icon="h(SaveOutlined)" html-type="submit" :loading="saveLoading">
                            保存配置
                        </a-button>
                    </a-form-item>
                </a-form>
            </a-spin>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue'
import { message } from 'ant-design-vue'
import { SaveOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { getPlatformConfig, saveConfig } from '@/api/config'

// 响应式数据
const formRef = ref()
const loading = ref(false)
const saveLoading = ref(false)

// 表单数据
const formState = reactive({
    id: '',
    config_name: '阿里云OSS配置',
    config_key: 'aliyun_oss',
    config_value: {
        accessKeyId: '',
        accessKeySecret: '',
        regionId: '',
        RoleArn: '',
        RoleSessionName: ''
    },
    description: '阿里云对象存储OSS基础配置信息'
})

// 表单验证规则
const rules = {
    config_value: {
        accessKeyId: [
            { required: true, message: '请输入AccessKey ID', trigger: 'blur' }
        ],
        accessKeySecret: [
            { required: true, message: '请输入AccessKey Secret', trigger: 'blur' }
        ],
        regionId: [
            { required: true, message: '请输入地域ID', trigger: 'blur' }
        ],
        RoleArn: [
            { required: true, message: '请输入角色ARN', trigger: 'blur' }
        ],
        RoleSessionName: [
            { required: true, message: '请输入角色会话名称', trigger: 'blur' }
        ]
    }
}

// 方法
const loadConfig = async () => {
    loading.value = true
    try {
        const response = await getPlatformConfig({
            config_key: 'aliyun_oss'
        })

        if (response.code === 200 && response.result) {
            // 如果有配置数据，则填充表单
            const config = response.result

            // 处理config_value，确保它是一个对象
            let configValue = config.config_value || {}
            if (typeof configValue === 'string') {
                try {
                    configValue = JSON.parse(configValue)
                } catch (e) {
                    console.error('解析config_value失败:', e)
                    configValue = {}
                }
            }

            Object.assign(formState, {
                id: config.id || '',
                config_name: config.config_name || '阿里云OSS配置',
                config_key: config.config_key || 'aliyun_oss',
                config_value: {
                    accessKeyId: configValue.accessKeyId || '',
                    accessKeySecret: configValue.accessKeySecret || '',
                    regionId: configValue.regionId || '',
                    RoleArn: configValue.RoleArn || '',
                    RoleSessionName: configValue.RoleSessionName || ''
                },
                description: config.description || '阿里云对象存储OSS基础配置信息'
            })
        }
    } catch (error) {
        console.error('加载配置失败:', error)
        message.error('加载配置失败')
    } finally {
        loading.value = false
    }
}

const onSubmit = async (values) => {
    saveLoading.value = true
    try {
        // 准备提交数据，将config_value转换为JSON字符串
        const submitData = {
            config_name: formState.config_name,
            config_key: formState.config_key,
            config_value: JSON.stringify(values.config_value),
            description: formState.description || ''
        }

        // 移除id字段，后端根据config_key判断新增还是更新
        delete submitData.id

        const response = await saveConfig(submitData)
        if (response.code === 200) {
            message.success('保存成功')
            // 重新加载配置
            await loadConfig()
        } else {
            message.error(response.message || '保存失败')
        }
    } catch (error) {
        console.error('保存失败:', error)
        message.error('保存失败')
    } finally {
        saveLoading.value = false
    }
}

const onFinishFailed = (errorInfo) => {
    console.log('表单验证失败:', errorInfo)
    message.error('请检查表单填写是否正确')
}

const onRefresh = () => {
    loadConfig()
}

// 生命周期
onMounted(() => {
    loadConfig()
})
</script>

<style scoped>
.aliyun-oss-config {
    .card-wrap {
        background: #fff;
        border-radius: 8px;
        padding: 24px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

        h3 {
            margin-bottom: 16px;
            color: #333;
            font-weight: 600;
        }
    }

    .mb10 {
        margin-bottom: 16px;
    }

    .mt10 {
        margin-top: 16px;
    }

    .animate-on-enter {
        animation: fadeInUp 0.6s ease-out;
    }

    .animate-delay-1 {
        animation-delay: 0.1s;
    }

    .animate-delay-2 {
        animation-delay: 0.2s;
    }

    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(20px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
}
</style>